#include "CAppStateGetName.h"
#include "CAppStateManager.h"

#include <iostream>

CAppStateGetName CAppStateGetName::Instance;

CAppStateGetName::CAppStateGetName() {
    Surf_BG = NULL;
    Surf_Message = NULL;
    SurfBlack = NULL;
}

void CAppStateGetName::OnActivate() {
    SurfBlack = CSurface::OnLoad("content/image/Black.jpg");
    SDL_SetAlpha(SurfBlack, SDL_SRCALPHA, 90);

    Surf_Message = CSurface::OnLoad("content/image/get_name.jpg");

    Surf_BG = CSurface::OnLoad("content/image/record_screen.jpg");
    Font = CFont::OnLoad("content/fonts/visitor2.ttf", 30);
    if (!CScore::Score.OnLoad("scores.xml"))
        printf("failed");

    Name = "";
}

void CAppStateGetName::OnDeactivate() {

}

void CAppStateGetName::OnLoop() {

}

char* StrToChar(std::string s) {
    char* buf = new char[s.length() + 1];
    strcpy(buf, s.c_str());
    return buf;
}

void CAppStateGetName::OnRender(SDL_Surface* Surf_Display) {
    CSurface::OnDraw(Surf_Display, Surf_BG, 0, 0);
    CScore::Score.OnDraw(Surf_Display, Font);
    CSurface::OnDraw(Surf_Display, SurfBlack, 0, 0);

    CSurface::OnDraw(Surf_Display, Surf_Message, Surf_Display->w / 2 - Surf_Message->w / 2, Surf_Display->h / 2 - Surf_Message->h / 2);

    CFont::OnDraw(Font, 0, StrToChar(Name), Surf_Display, Surf_Display->w / 2 - Surf_Message->w / 2 + 40, Surf_Display->h / 2 - Surf_Message->h / 2 + 120);

    if (!(StartTime + 1000 < SDL_GetTicks()) && StartTime != -1)
        CFont::OnDraw(Font, 2, "name is not available", Surf_Display, Surf_Display->w / 2 - Surf_Message->w / 2 + 40, Surf_Display->h / 2 - Surf_Message->h / 2 + 120);
}

CAppStateGetName* CAppStateGetName::GetInstance() {
    return &Instance;
}

void CAppStateGetName::OnKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {
    switch (sym) {
        case SDLK_RETURN:
            if (Name.size() > 0) {
                if (CScore::Score.AddScore(StrToChar(Name), CField::Field.Score, "scores.xml"))
                    CAppStateManager::SetActiveAppState(APPSTATE_SCORES);
                else {
                    Name = "";
                    StartTime = SDL_GetTicks();
                }
            }
        break;

        case SDLK_BACKSPACE:
            if (Name.size() > 0)
                Name.erase(Name.size() - 1, 1);
        break;

        default: break;
    }

    if (char(sym) - char('a') + 1 > 0 && char(sym) - char('a') + 1 < 34 && (StartTime + 1000 < SDL_GetTicks() || StartTime == -1)) {
        std::cout << "Sym: " << char(sym) << std::endl;
        Name += char(sym);
    }
}

